<?php

namespace App\Http\Controllers\API;

use App\Http\Requests\API\CreateOrderAPIRequest;
use App\Http\Requests\API\UpdateOrderAPIRequest;
use App\Models\Address;
use App\Models\Goods;
use App\Models\GoodsAttribute;
use App\Models\GoodsEvaluate;
use App\Models\Order;
use App\Models\OrderGoods;
use App\Models\PayRecord;
use App\Models\ReturnLog;
use App\Models\Role;
use App\Repositories\FreightRepository;
use App\Repositories\GoodsRepository;
use App\Repositories\OrderRepository;
use App\Repositories\WechatRepository;
use App\ZL\Controllers\ApiBaseController;
use EasyWeChat\Foundation\Application;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;

/**
 * Class OrderController
 * @package App\Http\Controllers\API
 */

class OrderAPIController extends ApiBaseController
{
    /** @var  OrderRepository */
    private $goodsRepository;
    private $orderRepository;
    private $wechatRepository;
    protected $model_name = 'App\Models\Order';
    protected $model_load_array = [
    ];
    protected $search_field_array = [
      'status','shipping_area','is_print','is_fresh_print','pay_status'
    ];

    public function __construct(OrderRepository $orderRepo, WechatRepository $wechatRepository, GoodsRepository $goodsRepository)
    {
        $this->orderRepository = $orderRepo;
        $this->wechatRepository = $wechatRepository;
        $this->goodsRepository = $goodsRepository;
    }

    public function authLimit(&$model)
    {
        $user_id = Auth::id();
        $shipping_status = request('shipping_status', null);
        $is_own = request('is_own', 0);
        $is_shipping_time = request('is_shipping_time', 0);
        $limit = [];
        $limit_time = 1;
//        if($is_shipping_time){
//        }

        if(isset($shipping_status)){
            //配送端初始化
//            $model = $model->where(function ($query){
//                $query->where([
//                    ['will_take',1],
//                    ['created_at','>=', "2017-11-26"],
//                ])->orWhere([
//                    ['shipping_at','>=', "2017-11-27"],
//                ]);
//            });
            $limit[] = ['pay_status', 1];
            if($shipping_status==1){
                $limit[] = ['shipping_status', 1];
                if($is_own)
                    $limit[] = ['pairing_id', $user_id];
                else{
                    $limit[] = ['status', '!=', 12];
                    $limit[] = ['pairing_id', 0];
                }
            }elseif ($shipping_status==2){
                $limit[] = ['shipping_status', 2];
                if($is_own)
                    $limit[] = ['verifier_id', $user_id];
                else{
                    $limit[] = ['verifier_id', 0];
                    $limit[] = ['status', '!=', 12];
                }
            }elseif ($shipping_status==3 || $shipping_status==4){
                $model = $model->whereIn('shipping_status',[3,4]);
                if($is_own){
                    $limit_time = 0;
                    $limit[] = ['courier_id', $user_id];
                }else{
                    $limit[] = ['status', '!=', 12];
                    $limit[] = ['courier_id', 0];
                }
            }elseif ($shipping_status==5){
                $model = $model->whereIn('shipping_status',[-1,5]);
                if($is_own)
                    $limit[] = ['courier_id', $user_id];
                else{
                    $limit[] = ['status', '!=', 12];
                    $limit[] = ['courier_id', 0];
                }
            }
            if($limit_time){
                $model = $model->where(function ($query){
                    $query->where([
                        ['will_take',1],
                        ['created_at','>=', "2017-11-26"],
                    ])->orWhere([
                        ['shipping_at','>=', date('Y-m-d')],
                        ['shipping_at','<=', date('Y-m-d',time()+3600*24)]
                    ]);
                });
            }
            $model = $model->orderBy('will_take','asc');
            $model = $model->where($limit)->orderBy('shipping_at','asc');
        }else{
            if($user_id){
                $limit[] = ['user_id', '=', $user_id];
            }
            $model = $model->where($limit)->orderBy('id','desc');
        }
        $is_fresh_print = request('is_fresh_print', null);
        if($is_fresh_print==1){
            $model = $model->where([
                ['is_fresh_print', 1],
                ['pay_status', 1],
                ['shipping_at','>=', date('Y-m-d')],
                ['shipping_at','<=', date('Y-m-d',time()+3600*24)]
            ]);
        }elseif($is_fresh_print===0 or $is_fresh_print==='0'){
            $model = $model->where([
                ['is_fresh_print', 0],
                ['pay_status', 1],
                ['shipping_at','>=', date('Y-m-d')],
                ['shipping_at','<=', date('Y-m-d',time()+3600*24)]
            ]);
        }
        return null;
    }

    public function index(Request $request)
    {

        $model = $this->modelPipeline([
            'modelGetAuthLimit',
            'modelGetSearch',
            'modelGetSort',
        ]);
        $model_data = clone $model;
        $count = $model->count();
        $list = $this->modelPipeline([
            'modelGetPageData',
            'collectionGetLoads',
        ],$model_data);

        $list->load('goods');
        $list->load('courier');
        $list->load('address');
        $_array = $list->toArray();
        foreach ($list as $k=>&$data) {
            $_goods = $data->goods;
            $_goods->load('goods');
            $_goods->load('attribute');
        }
        return responseZK(1,$list,'',['count'=>$count]);
    }

    public function _after_find(&$data)
    {
        $data->goods->load('goods');
        $data->address;
        $data->courier;
        $data->pairing;
        $data->verifier;
        $data->goods->load('attribute');
    }

    public function integralPay(Request $request)
    {
        $order = $this->orderRepository->add($request);
        if(is_string($order)){
            return responseZK(0,null,$order);
        }else{
            $this->orderRepository->handleGoodsNum($order);
            $this->orderRepository->success($order);
            return responseZK(1,$order->toArray(),'ok');
        }
    }

    public function checkArea(Request $request)
    {
        $goods_array = json_decode(request('goods','[]'), true);
        $goods = [];
        foreach ($goods_array as $k=>$v) {
            $goods[] = Goods::find($k);
        }
        $attributes_array = json_decode(request('attributes','[]'), true);
        $attributes = [];
        foreach ($attributes_array as $k=>$v) {
            $attributes[] = GoodsAttribute::find($k);
        }
        $freight_res = app()->build(FreightRepository::class);
        $res = $freight_res->checkArea($goods, $attributes, Address::find($request->address_id));
        if($res==null)
            return responseZK(1,$freight_res->calculate($goods, $attributes, Address::find($request->address_id)),'ok');
        else
            return responseZK(0,null,$res);
    }

    public function wxPay(Request $request)
    {
        $order = $this->orderRepository->add($request,2);
        if(is_string($order)){
            return responseZK(0,null,$order);
        }else{
            $this->orderRepository->handleGoodsNum($order);
            $pay_money = $order->pay_money;
            $out_trade_no =  date('Ymdhis', time()).substr(floor(microtime()*1000),0,1).rand(0,9);
            $payData = [
                'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
                "out_trade_no"	=> $out_trade_no,
                "total_fee"	=> ($pay_money*100),// 单位为元 ,最小为0.01
                "detail"	=> '小店铺商品 付款单号：'.$out_trade_no,
                "body"	=> '小店铺商品 付款单号：'.$out_trade_no,
                'openid'  => Auth::user()->xcx_openid, // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
            ];
            $wxRecord = PayRecord::create([
                'order_id'=>$order->id,
                'amount'=>$pay_money,
                'channel'=>'wx_xcx',
                'out_trade_no'=>$out_trade_no,
                'trade_state'=>'INIT',
                'payer_id'=>Auth::id()
            ]);
            $e_order = new \EasyWeChat\Payment\Order($payData);
            $app = new Application(config('easywechat'));
            $payment = $app->payment;
            $result = $payment->prepare($e_order);
            if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
                $prepayId = $result->prepay_id;
                $config = $payment->configForJSSDKPayment($prepayId);
                return responseZK(1,$config, 'ok');
            }
            return responseZK(0,null,'参数有误');
        }
    }

    public function wechatPay(Request $request)
    {
        $order = $this->orderRepository->add($request,2);
        if(is_string($order)){
            return responseZK(0,null,$order);
        }else{
            $this->orderRepository->handleGoodsNum($order);
            $pay_money = $order->pay_money;
            $out_trade_no =  date('Ymdhis', time()).substr(floor(microtime()*1000),0,1).rand(0,9);
            $payData = [
                'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
                "out_trade_no"	=> $out_trade_no,
                "total_fee"	=> ($pay_money*100),// 单位为元 ,最小为0.01
                "detail"	=> '你好菜商品 付款单号：'.$out_trade_no,
                "body"	=> '你好菜商品 付款单号：'.$out_trade_no,
                'openid'           => Auth::user()->openid, // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
            ];
            $wxRecord = PayRecord::create([
                'order_id'=>$order->id,
                'amount'=>$pay_money,
                'channel'=>'wx_xcx',
                'out_trade_no'=>$out_trade_no,
                'trade_state'=>'INIT',
                'payer_id'=>Auth::id()
            ]);
            $e_order = new \EasyWeChat\Payment\Order($payData);
            $app = new Application(config('wechat'));
            $payment = $app->payment;
            $result = $payment->prepare($e_order);
            if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
                $prepayId = $result->prepay_id;
                $config = $payment->configForJSSDKPayment($prepayId);
                return responseZK(1,$config, 'ok');
            }
            return responseZK(0,null,'参数有误');
        }
    }

    public function notification(Request $request)
    {
        $app = new Application(config('easywechat'));
        $payment = $app->payment;
        $response = $app->payment->handleNotify(function($notify, $successful)use($payment) {
            // 你的逻辑
            DB::table('notifications')->insert([
                'created_at' => date('Y-m-d H:i:s'),
                'json' => json_encode($notify, 256),
                'title' => 'notification'
            ]);
            $out_trade_no = $notify->out_trade_no;
            $wxpayRecord = PayRecord::where('out_trade_no', $out_trade_no)->first();
            $done_orders = [];
            if (!$wxpayRecord) { // 如果订单不存在
                return 'Order not exist.'; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            if ($successful) {
                if($wxpayRecord->trade_state == 'SUCCESS'){
                    return true;
                }
                $wxpayRecord->trade_state = 'SUCCESS';
                $wxpayRecord->notify_at = date('Y-m-d H:i:s');
                $wxpayRecord->transaction_id = $notify->transaction_id;
                $wxpayRecord->payer_openid = $notify->openid;
                $wxpayRecord->notify_data = json_encode($notify, 256);
                $wxpayRecord->save();
                $this->orderRepository->success($wxpayRecord->order);

                $bon_str = $wxpayRecord->order->bonus?$wxpayRecord->order->bonus->name:'无';
                $order_str = '总价:'.$wxpayRecord->order->price.' 商品数量:'.$wxpayRecord->order->goods_number.' 支付积分:'.$wxpayRecord->order->use_integral.' 使用优惠券:'.$bon_str.' 实际支付:'.$wxpayRecord->amount;
                if($wxpayRecord->order->address)
                    $order_str .= '地址：'.$wxpayRecord->order->address->address.' 收货人:'.$wxpayRecord->order->address->name.' '.$wxpayRecord->order->address->phone;

                $role = Role::find(2);
                $url = route('order.info',[$wxpayRecord->order_id]);
                if($role->users->count()>0){
                    foreach ($role->users as $_u) {
//                        $templateId = 'kVv8ODBrEdesXqqi2wFZuki8AB-54wfvZSa6ns1_PYQ';
                        $templateId = 'h9_UnIGDf3hsi5p70STeXdudusVUSQqBEexz6ss_83E';
                        $array = [
                            'first'=>'尊敬的管理员，您有新的订单',
                            'keyword1'=>$wxpayRecord->order->sn,
                            'keyword2'=>date('Y-m-d H:i:s'),
                            'remark'=>$order_str,
                        ];
                        $this->wechatRepository->sendTempMsg($_u->openid,$templateId,$url,$array);
                    }
                }
                $this->orderRepository->sendParentCaijin($wxpayRecord->order);
            } else { // 用户支付失败
                $wxpayRecord->trade_state = 'FAIL';
                $wxpayRecord->notify_at = date('Y-m-d H:i:s');
                $this->orderRepository->error($wxpayRecord->order);
            }
            $wxpayRecord->save(); // 保存wx交易记录
            return true; // 返回处理完成
        });
        return $response;
    }

    public function notificationByWechat(Request $request)
    {
        $app = new Application(config('wechat'));
        $payment = $app->payment;
        $response = $app->payment->handleNotify(function($notify, $successful)use($payment) {
            // 你的逻辑
            DB::table('notifications')->insert([
                'created_at' => date('Y-m-d H:i:s'),
                'json' => json_encode($notify, 256),
                'title' => 'wechat_notification'
            ]);
            $out_trade_no = $notify->out_trade_no;
            $wxpayRecord = PayRecord::where('out_trade_no', $out_trade_no)->first();
            $done_orders = [];
            if (!$wxpayRecord) { // 如果订单不存在
                return 'Order not exist.'; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            if ($successful) {
                if($wxpayRecord->trade_state == 'SUCCESS'){
                    return true;
                }
                $wxpayRecord->trade_state = 'SUCCESS';
                $wxpayRecord->notify_at = date('Y-m-d H:i:s');
                $wxpayRecord->transaction_id = $notify->transaction_id;
                $wxpayRecord->payer_openid = $notify->openid;
                $wxpayRecord->notify_data = json_encode($notify, 256);
                $wxpayRecord->save();
                $this->orderRepository->success($wxpayRecord->order);

                $bon_str = $wxpayRecord->order->bonus?$wxpayRecord->order->bonus->name:'无';
                $order_str = '总价:'.$wxpayRecord->order->price.' 商品数量:'.$wxpayRecord->order->goods_number.' 支付积分:'.$wxpayRecord->order->use_integral.' 使用优惠券:'.$bon_str.' 实际支付:'.$wxpayRecord->amount;
                if($wxpayRecord->order->address)
                    $order_str .= '地址：'.$wxpayRecord->order->address->address.' 收货人:'.$wxpayRecord->order->address->name.' '.$wxpayRecord->order->address->phone;

                $role = Role::find(2);
                $url = route('order.info',[$wxpayRecord->order_id]);
                if($role->users->count()>0){
                    foreach ($role->users as $_u) {
//                        $templateId = 'kVv8ODBrEdesXqqi2wFZuki8AB-54wfvZSa6ns1_PYQ';
                        $templateId = 'h9_UnIGDf3hsi5p70STeXdudusVUSQqBEexz6ss_83E';
                        $array = [
                            'first'=>'尊敬的管理员，您有新的订单',
                            'keyword1'=>$wxpayRecord->order->sn,
                            'keyword2'=>date('Y-m-d H:i:s'),
                            'remark'=>$order_str,
                        ];
                        $this->wechatRepository->sendTempMsg($_u->openid,$templateId,$url,$array);
                    }
                }
                $this->orderRepository->sendParentCaijin($wxpayRecord->order);
            } else { // 用户支付失败
                $wxpayRecord->trade_state = 'FAIL';
                $wxpayRecord->notify_at = date('Y-m-d H:i:s');
                $this->orderRepository->error($wxpayRecord->order);
            }
            $wxpayRecord->save(); // 保存wx交易记录
            return true; // 返回处理完成
        });
        return $response;
    }

    public function getPayConfigByOrder()
    {
        $order_id = request('order_id', null);
        $order = Order::find($order_id);
        if($order) {
            if($order->pay_status)
                return responseZK(0, null, '订单已付款');
//            $old_record =order->payRecord;
//            if($old_record)
//                $old_record-> $delete();
            $pay_money = $order->pay_money;
            $out_trade_no =  date('Ymdhis', time()).substr(floor(microtime()*1000),0,1).rand(0,9);
            $payData = [
                'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
                "out_trade_no"	=> $out_trade_no,
                "total_fee"	=> $pay_money*100,// 单位为元 ,最小为0.01
                "detail"	=> '你好菜商品 付款单号：'.$out_trade_no,
                "body"	=> '你好菜商品 付款单号：'.$out_trade_no,
                'openid'           => Auth::user()->xcx_openid, // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
            ];
            $wxRecord = PayRecord::create([
                'order_id'=>$order->id,
                'amount'=>$pay_money,
                'channel'=>'wx_xcx',
                'out_trade_no'=>$out_trade_no,
                'trade_state'=>'INIT',
                'payer_id'=>Auth::id()
            ]);
            $e_order = new \EasyWeChat\Payment\Order($payData);
            $app = new Application(config('easywechat'));
            $payment = $app->payment;
            $result = $payment->prepare($e_order);
            if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
                $prepayId = $result->prepay_id;
                $config = $payment->configForJSSDKPayment($prepayId);
                return responseZK(1,$config, 'ok');
            }
        }
        return responseZK(0, null, '找不到订单');
    }

    public function getWechatPayConfigByOrder()
    {
        $order_id = request('order_id', null);
        $order = Order::find($order_id);
        if($order) {
            if($order->pay_status)
                return responseZK(0, null, '订单已付款');
//            $old_record =order->payRecord;
//            if($old_record)
//                $old_record-> $delete();
            $pay_money = $order->pay_money;
            $out_trade_no =  date('Ymdhis', time()).substr(floor(microtime()*1000),0,1).rand(0,9);
            $payData = [
                'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
                "out_trade_no"	=> $out_trade_no,
                "total_fee"	=> $pay_money*100,// 单位为元 ,最小为0.01
                "detail"	=> '你好菜商品 付款单号：'.$out_trade_no,
                "body"	=> '你好菜商品 付款单号：'.$out_trade_no,
                'openid'           => Auth::user()->openid, // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
            ];
            $wxRecord = PayRecord::create([
                'order_id'=>$order->id,
                'amount'=>$pay_money,
                'channel'=>'wx_wechat',
                'out_trade_no'=>$out_trade_no,
                'trade_state'=>'INIT',
                'payer_id'=>Auth::id()
            ]);
            $e_order = new \EasyWeChat\Payment\Order($payData);
            $app = new Application(config('wechat'));
            $payment = $app->payment;
            $result = $payment->prepare($e_order);
            if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
                $prepayId = $result->prepay_id;
                $config = $payment->configForJSSDKPayment($prepayId);
                return responseZK(1,$config, 'ok');
            }
        }
        return responseZK(0, null, '找不到订单');
    }

    public function getGoodsTimelySort()
    {
        $orderGoods_ids = DB::table('order_goods')
            ->join('orders', 'orders.id', '=', 'order_goods.order_id')
            ->join('goods', 'goods.id', '=', 'order_goods.goods_id')
            ->select('order_goods.*')
            ->where([
                ['goods.is_timely_sort', 1],
            ])
            ->whereNull('orders.pairing_at')
            ->where(function($query){
                $query->where([
                    ['orders.status',2],
                    ['orders.shipping_at','>=', date('Y-m-d')],
                    ['orders.shipping_at','<=', date('Y-m-d',time()+3600*24)]
                ]);
                $query->orWhere('will_take',1);
            })
            ->orderBy('orders.will_take','asc')
            ->orderBy('orders.shipping_at','asc')
            ->pluck('id');

        $orderGoods = OrderGoods::whereIn('id', $orderGoods_ids->toArray())->get();
        $orderGoods->load('goods');
        $orderGoods->load('attribute');
        $orderGoods->load('order');
        foreach ($orderGoods as $v) {
            $v->order->address;
        }
        return responseZK(1, $orderGoods->toArray());
    }

    public function payCancel()
    {
        $order_id = request('order_id', null);
        $order = Order::find($order_id);
        if($order) {
        }
        return responseZK(0, null, '找不到订单');
    }

    public function returnOrder()
    {
        $order_id = request('order_id', null);
        $order = Order::find($order_id);
        if($order) {
            $price = $order->pay_money;
            $num = $order->goods_num;
            foreach ($order->goods as $v) {
                if($v->status==11 || $v->status==12){
                    $num -= $v->number;
                    $price -= $v->price;
                }
            }
            if($order->status!='11'){
                $order->status=11;
                $order->save();
                ReturnLog::create([
                    'order_id'=>$order->id,
                    'type'=>1,
                    'num'=>$num,
                    'price'=>$price,
                    'status'=>1,
                ]);
            }
            return responseZK(1);
        }
        return responseZK(0, null, '找不到订单');
    }

    public function returnGoods()
    {
        $orderGoods_id = request('orderGoods_id', null);
        $order_id = request('order_id', null);
        $order = Order::find($order_id);
        $orderGoods = OrderGoods::find($orderGoods_id);
        if(!$order_id || !$order){
            return responseZK(0, null, '找不到订单');
        }
        if(!$orderGoods_id || !$orderGoods){
            return responseZK(0, null, '找不到订单下的商品');
        }
        $number = request('number', $orderGoods->number);
        if($orderGoods->status!=11 and $orderGoods->status!=12){
            $orderGoods->status=11;
            $orderGoods->apply_return_number += $number;
            $orderGoods->save();
            ReturnLog::create([
                'order_id'=>$order->id,
                'type'=>2,
                'status'=>1,
                'orderGoods_id'=>$orderGoods_id,
                'price'=>$orderGoods->price,
                'goods_id'=>$orderGoods->goods_id,
                'attribute_id'=>$orderGoods->attribute_id,
                'number'=>$number,
            ]);
            $ok = 0;
            foreach ($order->goods as $g) {
                if($g->status==1)
                    $ok = 1;
            }
            if($ok==0){
                $order->status=11;
                $order->save();
            }
        }
        return responseZK(1);
    }

    public function setPrintState()
    {
        $ids = request('ids',[]);
        if(!empty($ids)){
            $ids = json_decode($ids,true);
            Order::whereIn('id',$ids)->update(['is_print'=>1]);
        }
        return responseZK(1);
    }

    public function setFreshPrintState()
    {
        $ids = request('ids',[]);
        if(!empty($ids)){
            $ids = json_decode($ids,true);
            Order::whereIn('id',$ids)->update(['is_fresh_print'=>1]);
        }
        return responseZK(1);
    }

    public function rob()
    {
        $user_id = Auth::id();
        $order_id = request('order_id',0);
        if(!$user_id)
            return responseZK(0, null, '请先登录');
        if(!$order_id)
            return responseZK(0, null, '没有缺少订单id');
        $order = Order::find($order_id);
        if(!$order)
            return responseZK(0, null, '找不到订单');
        if($order->shipping_status==1){
            if($order->pairing_id){
                return responseZK(0, null, '订单已经在配单中');
            }else{
                $order->pairing_id = $user_id;
                $order->pairing_tob_at = date('Y-m-d H:i:s');
                $order->save();
            }
        }elseif ($order->shipping_status==2){
            if($order->verifier_id){
                return responseZK(0, null, '订单已经在验单中');
            }else{
                $order->verifier_id = $user_id;
                $order->verify_tob_at = date('Y-m-d H:i:s');
                $order->save();
            }
        }elseif ($order->shipping_status==3){
            if($order->courier_id){
                return responseZK(0, null, '订单已有人配送');
            }else{
                $order->courier_id = $user_id;
                $order->shipping_rob_at = date('Y-m-d H:i:s');
                $order->save();
            }
        }else{
            return responseZK(0, null, '订单状态出错');
        }
        return responseZK(1);
    }

    public function robOff()
    {
        $user_id = Auth::id();
        $order_id = request('order_id',0);
        if(!$order_id)
            return responseZK(0, null, '没有缺少订单id');
        $order = Order::find($order_id);
        if(!$order)
            return responseZK(0, null, '找不到订单');
        if($order->shipping_status==1 && $order->pairing_id){
            $order->pairing_id = 0;
            $order->pairing_tob_at = null;
            $order->save();
        }elseif ($order->shipping_status==2 && $order->verifier_id){
            $order->verifier_id = 0;
            $order->verify_tob_at = null;
            $order->save();
        }elseif ($order->shipping_status==3 && $order->courier_id){
            $order->courier_id = 0;
            $order->shipping_rob_at = null;
            $order->save();
        }else{
            return responseZK(0, null, '订单不可退回');
        }
        return responseZK(1);
    }

    public function pairingOk()
    {
        $order_id = request('order_id',0);
        if(!$order_id)
            return responseZK(0, null, '没有缺少订单id');
        $order = Order::find($order_id);
        if(!$order)
            return responseZK(0, null, '找不到订单');
        if($order->pairing_id==0){
            return responseZK(0, null, '还没派单员接单');
        }
        if($order->shipping_status==1){
            $pairing_ids = request('pairing_ids');
            $pairing_arr = explode(',', $pairing_ids);
            if(!empty($pairing_arr))
                OrderGoods::whereIn('id', $pairing_arr)->update(['pairing_status'=>1]);
            $order->shipping_status = 2;
            $order->pairing_at = date('Y-m-d H:i:s');
            $order->save();
            return responseZK(1);
        }else{
            return responseZK(0, null, '订单状态已改变');
        }
    }

    public function verifyOk()
    {
        $order_id = request('order_id',0);
        $verify_desc = request('verify_desc',null);
        if(!$order_id)
            return responseZK(0, null, '没有缺少订单id');
        $order = Order::find($order_id);
        if(!$order)
            return responseZK(0, null, '找不到订单');
        if($order->verifier_id==0){
            return responseZK(0, null, '还没验单员接单');
        }
        if($order->shipping_status==2){
            $order->shipping_status = 3;
            $order->verify_desc = $verify_desc;
            $order->verify_at = date('Y-m-d H:i:s');
            $order->save();
            return responseZK(1);
        }else{
            return responseZK(0, null, '订单状态已改变');
        }
    }

    public function shippingStart()
    {
        $order_id = request('order_id',0);
        if(!$order_id)
            return responseZK(0, null, '没有缺少订单id');
        $order = Order::find($order_id);
        if(!$order)
            return responseZK(0, null, '找不到订单');
        if($order->courier_id==0){
            return responseZK(0, null, '还没配送员接单');
        }
        if($order->shipping_status==3){
            $order->status = 3;
            $order->shipping_status = 4;
            $order->real_shipping_at = date('Y-m-d H:i:s');
            $order->save();
            return responseZK(1);
        }else{
            return responseZK(0, null, '订单状态已改变');
        }
    }

    public function shippingEnd()
    {
        $order_id = request('order_id',0);
        if(!$order_id)
            return responseZK(0, null, '没有缺少订单id');
        $order = Order::find($order_id);
        if(!$order)
            return responseZK(0, null, '找不到订单');
        if(!$order->real_shipping_at)
            return responseZK(0, null, '订单没有开始配送');
        if($order->shipping_status==4){
            $order->status = 4;
            $order->shipping_status = 5;
            $order->real_shipping_end_at = date('Y-m-d H:i:s');
            $order->save();
            return responseZK(1);
        }else{
            return responseZK(0, null, '订单状态已改变');
        }
    }

    public function cancel()
    {
        $order_id = request('order_id',0);
        if(!$order_id)
            return responseZK(0, null, '没有缺少订单id');
        $order = Order::find($order_id);
        if(!$order)
            return responseZK(0, null, '找不到订单');
        $order->shipping_status = -1;
        $order->save();
        return responseZK(1);
    }

    public function setShippingArea()
    {
        $order_id = request('order_id',0);
        $area = request('shipping_area',null);
        if(!$order_id || !$area)
            return responseZK(0, null, '缺少参数');
        $order = Order::find($order_id);
        if(!$order)
            return responseZK(0, null, '找不到订单');
        $order->shipping_area = $area;
        $order->save();
        return responseZK(1);
    }

    public function evaluate()
    {
        $order_id = request('order_id');
        $user_id = Auth::id();
        $evaluate = json_decode(request('evaluate'), true);
        $order = Order::find($order_id);
        if(!$evaluate || !$order_id || !$order)
            return responseZK(0,null,'缺少参数');
        if($order->status==6)
            return responseZK(0,null,'订单已评价');

        foreach ($evaluate['goods'] as $v) {
            GoodsEvaluate::create([
               'order_id'=>$order_id,
               'user_id'=>$user_id,
               'goods_id'=>$v['goods_id'],
               'level'=>$v['level'],
               'content'=>$v['content']?$v['content']:'默认好评',
               'is_anonym'=>$v['is_anonym'],
               'pictures'=>json_encode($v['pictures']),
            ]);
        }
        foreach ($evaluate['attribute'] as $v) {
            GoodsEvaluate::create([
                'order_id'=>$order_id,
                'user_id'=>$user_id,
                'goods_id'=>$v['goods_id'],
                'attribute_id'=>$v['attribute_id'],
                'level'=>$v['level'],
                'content'=>$v['content']?$v['content']:'默认好评',
                'is_anonym'=>$v['is_anonym'],
                'pictures'=>json_encode($v['pictures']),
            ]);
        }
        Order::where('id',$order_id)->update(['status'=>6]);
        return responseZK(1);
    }

    public function test()
    {
//        $this->wechatRepository->dumpUser();
        $wxpayRecord = PayRecord::find(26);
    }
}
